<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <a-spin :spinning="confirmLoading">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="工程名称">
              <a-input v-model="queryParam.projectName" placeholder="请输入工程名称" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="状态">
              <a-select v-model="queryParam.status" placeholder="请选择状态" allowClear>
                <a-select-option :value="0">未开始</a-select-option>
                <a-select-option :value="1">进行中</a-select-option>
                <a-select-option :value="2">已完成</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
      
      <a-divider style="margin: 10px 0" />
      
      <div class="table-operator" style="margin-bottom: 10px">
        <a-button type="primary" icon="plus" @click="handleAddProject">新增工程</a-button>
      </div>
      
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio'}"
        @change="handleTableChange">
        
        <!-- 状态列 -->
        <template slot="statusSlot" slot-scope="text">
          <a-tag v-if="text == 0" color="blue">未开始</a-tag>
          <a-tag v-else-if="text == 1" color="green">进行中</a-tag>
          <a-tag v-else-if="text == 2" color="orange">已完成</a-tag>
          <a-tag v-else color="gray">未知</a-tag>
        </template>
        
        <!-- 地区列 -->
        <template slot="areaSlot" slot-scope="text, record">
          {{ getAreaText(record) }}
        </template>
      </a-table>
    </a-spin>
    
    <!-- 工程新增模态框 -->
    <project-modal ref="projectModal" @ok="handleProjectModalOk"></project-modal>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import { projectByCustomer } from '@/api/crm'
import ProjectModal from '@/views/crm/modules/ProjectModal'

export default {
  name: 'ProjectSelectModal',
  components: {
    ProjectModal
  },
  data() {
    return {
      title: '选择工程',
      visible: false,
      customerId: '',
      confirmLoading: false,
      selectedRowKeys: [],
      selectedRows: [],
      
      // 查询参数
      queryParam: {
        projectName: '',
        status: undefined
      },
      
      // 表格列定义
      columns: [
        {
          title: '工程名称',
          dataIndex: 'projectName',
          align: 'center',
          width: 200
        },
        {
          title: '联系人',
          dataIndex: 'contactPerson',
          align: 'center',
          width: 100
        },
        {
          title: '联系电话',
          dataIndex: 'contactPhone',
          align: 'center',
          width: 120
        },
        {
          title: '地区',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'areaSlot' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' }
        }
      ],
      
      // 数据源
      dataSource: [],
      
      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      
      loading: false
    }
  },
  methods: {
    show(customerId) {
      this.customerId = customerId
      this.visible = true
      this.loadData(1)
    },
    
    loadData(arg) {
      if (!this.customerId) {
        this.$message.warning('未选择客户，无法加载工程列表')
        return
      }
      
      if (arg === 1) {
        this.ipagination.current = 1
      }
      
      this.loading = true
      
      // 构建查询参数
      let params = {
        customerId: this.customerId,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        ...this.queryParam
      }
      
      // 调用后端接口查询工程列表
      projectByCustomer(params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records || []
          this.ipagination.total = res.result.total || 0
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 搜索
    searchQuery() {
      this.loadData(1)
    },
    
    // 重置
    searchReset() {
      this.queryParam = {
        projectName: '',
        status: undefined
      }
      this.loadData(1)
    },
    
    // 表格变化事件
    handleTableChange(pagination) {
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      this.loadData()
    },
    
    // 选择行变化事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    
    // 获取地区文本
    getAreaText(record) {
      const province = record.provinceName || ''
      const city = record.cityName || ''
      const area = record.areaName || ''
      
      if (province || city || area) {
        return [province, city, area].filter(Boolean).join('/')
      }
      
      return record.address || '未设置地区'
    },
    
    // 确认选择
    handleOk() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择一个工程')
        return
      }
      
      this.$emit('ok', this.selectedRows[0])
      this.handleCancel()
    },
    
    // 取消选择
    handleCancel() {
      this.visible = false
      this.customerId = ''
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    
    // 新增工程
    handleAddProject() {
      // 准备客户数据
      const customerData = {
        customerId: this.customerId
      }
      
      // 打开新增工程模态框
      this.$refs.projectModal.add(customerData)
      this.$refs.projectModal.title = '新增工程'
    },
    
    // 工程模态框确认回调
    handleProjectModalOk() {
      this.loadData()
    }
  }
}
</script>

<style scoped>
</style> 